<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
	<title>交流</title>
	<link th:href="@{/css/bootstrap.min.css?v=3.3.7}" rel="stylesheet"/>
	<link rel="stylesheet" th:href="@{/rolling/css/rolling.css}">
	<link rel="stylesheet" th:href="@{/stylesheets/style.css}">
	<script th:src="@{/js/jquery.min.js?v=3.6.0}"></script>
	<script th:src="@{/js/bootstrap.min.js?v=3.3.7}"></script>
	<script th:src="@{/ajax/libs/layer/layer.min.js?v=3.5.1}"></script>
	<script th:src="@{/ajax/libs/layui-v2.6.8/layui/layui.js}"></script>
	<script type="text/javascript" th:src="@{/rolling/js/rolling.js}"></script>
	<script type="text/javascript" th:src="@{/javascripts/Public.js}"></script>
	<style>
		.loaderbox {
			display: none;
			width: 100%;
			text-align: center;
			padding: 10px;
			margin: 5px auto;
			color: #000 !important;
			font-size: 13px;
			font-weight: 400;
			vertical-align: middle;
			border: 1px solid #ddd;
			background-color: rgba(238, 238, 238, 0.7);
			-webkit-border-radius: 2px;
			-moz-border-radius: 2px;
			-ms-border-radius: 2px;
			-o-border-radius: 2px;
			border-radius: 2px;
			-webkit-box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1);
			-moz-box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1);
			box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1);
		}
		.loaderbox .loading-activity {
			position: absolute;
			left: 30%;
			width: 18px;
			height: 18px;
			border: solid 2px transparent;
			border-top-color: #000;
			border-left-color: #000;
			border-radius: 10px;
			-webkit-animation: pace-spinner 400ms linear infinite;
			-moz-animation: pace-spinner 400ms linear infinite;
			-ms-animation: pace-spinner 400ms linear infinite;
			-o-animation: pace-spinner 400ms linear infinite;
			animation: pace-spinner 400ms linear infinite;
		}
		@media (max-width: 767px) {
			.loading-activity {
				width: 18px;
				height: 18px;
			}
		}

		@-ms-keyframes pace-spinner {
			0% {
				-ms-transform: rotate(0deg);
				transform: rotate(0deg);
			}

			100% {
				-ms-transform: rotate(360deg);
				transform: rotate(360deg);
			}
		}

		@keyframes pace-spinner {
			0% {
				transform: rotate(0deg);
			}

			100% {
				transform: rotate(360deg);
			}
		}
		/*转圈动画结束*/
	</style>
</head>
<body class="room">
	<div  class="scrollbar-macosx">
		<div class="header">
			<div style="width: 100%;text-align: center;height: 100%">
				<span th:if="${linkUserName!=null}" th:text="${linkUserName+'&nbsp;&nbsp;'}"   style="font-size: 15px;font-weight: 700;">用户名</span>
				<span th:if="${onlineStatus=='0'}"><span style="background-color: red;display: inline-block;width: 10px;height: 10px;border-radius: 10px"></span><span style="font-size: 12px;color: #999aaa">&nbsp;离线</span></span>
				<span th:if="${onlineStatus=='1'}"><span style="background-color: #1DDF80;display: inline-block;width: 10px;height: 10px;border-radius: 10px"></span><span style="font-size: 12px;color: #999aaa">&nbsp;在线</span></span>
			</div>
			<div class="loaderbox"><div class="loading-activity"></div>加载中，请稍候...</div>
		</div>
		<div class="main container">
			<div class="col-md-12">
				<div  class="chat-end" style="width: 100%;text-align: center;display: none;margin-top: 10px">
					<span>没有更多了</span>
				</div>
				<ul class="chat_info">

				</ul>
			</div>
		</div>
		<div class="input">
			<div class="center">
				<div class="tools">
					<span class="glyphicon glyphicon-heart face_btn"></span>
<!--
6-->
					<input type="file" class="imgFileBtn hidden" accept="image/*">
					<div class="faces popover fade top in">
						<div class="arrow"></div>
						<h3 class="popover-title">表情包</h3>
						<div class="popover-content scrollbar-macosx">
							<img th:src="@{/img/chat/face/1.gif}" alt="1">
							<img th:src="@{/img/chat/face/2.gif}" alt="2">
							<img th:src="@{/img/chat/face/3.gif}" alt="3">
							<img th:src="@{/img/chat/face/4.gif}" alt="4">
							<img th:src="@{/img/chat/face/5.gif}" alt="5">
							<img th:src="@{/img/chat/face/6.gif}" alt="6">
							<img th:src="@{/img/chat/face/7.gif}" alt="7">
							<img th:src="@{/img/chat/face/8.gif}" alt="8">
							<img th:src="@{/img/chat/face/9.gif}" alt="9">
							<img th:src="@{/img/chat/face/10.gif}" alt="10">
							<img th:src="@{/img/chat/face/11.gif}" alt="11">
							<img th:src="@{/img/chat/face/12.gif}" alt="12">
							<img th:src="@{/img/chat/face/13.gif}" alt="13">
							<img th:src="@{/img/chat/face/14.gif}" alt="14">
							<img th:src="@{/img/chat/face/15.gif}" alt="15">
							<img th:src="@{/img/chat/face/16.gif}" alt="16">
							<img th:src="@{/img/chat/face/17.gif}" alt="17">
							<img th:src="@{/img/chat/face/18.gif}" alt="18">
							<img th:src="@{/img/chat/face/19.gif}" alt="19">
							<img th:src="@{/img/chat/face/20.gif}" alt="20">
							<img th:src="@{/img/chat/face/21.gif}" alt="21">
							<img th:src="@{/img/chat/face/22.gif}" alt="22">
							<img th:src="@{/img/chat/face/23.gif}" alt="23">
							<img th:src="@{/img/chat/face/24.gif}" alt="24">
							<img th:src="@{/img/chat/face/25.gif}" alt="25">
							<img th:src="@{/img/chat/face/26.gif}" alt="26">
							<img th:src="@{/img/chat/face/27.gif}" alt="27">
							<img th:src="@{/img/chat/face/28.gif}" alt="28">
							<img th:src="@{/img/chat/face/29.gif}" alt="29">
							<img th:src="@{/img/chat/face/30.gif}" alt="30">
							<img th:src="@{/img/chat/face/31.gif}" alt="31">
							<img th:src="@{/img/chat/face/32.gif}" alt="32">
							<img th:src="@{/img/chat/face/33.gif}" alt="33">
							<img th:src="@{/img/chat/face/34.gif}" alt="34">
							<img th:src="@{/img/chat/face/35.gif}" alt="35">
							<img th:src="@{/img/chat/face/36.gif}" alt="36">
							<img th:src="@{/img/chat/face/37.gif}" alt="37">
							<img th:src="@{/img/chat/face/38.gif}" alt="38">
							<img th:src="@{/img/chat/face/39.gif}" alt="39">
							<img th:src="@{/img/chat/face/40.gif}" alt="40">
							<img th:src="@{/img/chat/face/41.gif}" alt="41">
							<img th:src="@{/img/chat/face/42.gif}" alt="42">
							<img th:src="@{/img/chat/face/43.gif}" alt="43">
							<img th:src="@{/img/chat/face/44.gif}" alt="44">
							<img th:src="@{/img/chat/face/45.gif}" alt="45">
							<img th:src="@{/img/chat/face/46.gif}" alt="46">
							<img th:src="@{/img/chat/face/47.gif}" alt="47">
							<img th:src="@{/img/chat/face/48.gif}" alt="48">
							<img th:src="@{/img/chat/face/49.gif}" alt="49">
							<img th:src="@{/img/chat/face/50.gif}" alt="50">
							<img th:src="@{/img/chat/face/51.gif}" alt="51">
							<img th:src="@{/img/chat/face/52.gif}" alt="52">
							<img th:src="@{/img/chat/face/53.gif}" alt="53">
							<img th:src="@{/img/chat/face/54.gif}" alt="54">
							<img th:src="@{/img/chat/face/55.gif}" alt="55">
							<img th:src="@{/img/chat/face/56.gif}" alt="56">
							<img th:src="@{/img/chat/face/57.gif}" alt="57">
							<img th:src="@{/img/chat/face/58.gif}" alt="58">
							<img th:src="@{/img/chat/face/59.gif}" alt="59">
							<img th:src="@{/img/chat/face/60.gif}" alt="60">
							<img th:src="@{/img/chat/face/61.gif}" alt="61">
							<img th:src="@{/img/chat/face/62.gif}" alt="62">
							<img th:src="@{/img/chat/face/63.gif}" alt="63">
							<img th:src="@{/img/chat/face/64.gif}" alt="64">
							<img th:src="@{/img/chat/face/65.gif}" alt="65">
							<img th:src="@{/img/chat/face/66.gif}" alt="66">
							<img th:src="@{/img/chat/face/67.gif}" alt="67">
							<img th:src="@{/img/chat/face/68.gif}" alt="68">
							<img th:src="@{/img/chat/face/69.gif}" alt="69">
							<img th:src="@{/img/chat/face/70.gif}" alt="70">
							<img th:src="@{/img/chat/face/71.gif}" alt="71">
							<img th:src="@{/img/chat/face/72.gif}" alt="72">
							<img th:src="@{/img/chat/face/73.gif}" alt="73">
							<img th:src="@{/img/chat/face/74.gif}" alt="74">
							<img th:src="@{/img/chat/face/75.gif}" alt="75">
						</div>
					</div>
				</div>
				<div class="text">
					<div class="col-xs-10 col-sm-11">
						<input type="text" class="form-control" placeholder="输入聊天信息...">
					</div>
					<div class="col-xs-2 col-sm-1">
						<a id="subxx" role="button">
							<span class="glyphicon glyphicon-share-alt"></span></a>
					</div>
				</div>
			</div>
		</div>
	</div>
</body>

<script th:inline="javascript">
	var userId = [[${userId}]]
	var otherSideUserId = [[${otherSideUserId}]]
	var userName = [[${userName}]]
	var avatar = [[${avatar}]]

	var dataTable = [[${dataTable}]]
	//聊天总记录数
	var total = dataTable.total
	//每页多少条
	var pageSize = 5
	//一共有多少页
	var pageAll = Math.ceil(total/pageSize)
	console.log("总页数"+pageAll)
	//当前页数
	var page = 2
	var websocket = null;
	//判断当前浏览器是否支持WebSocket, 主要此处要更换为自己的地址  注意测试环境为ws://localhost:80 生产环境wss://wuyujitang.top:443
	if ('WebSocket' in window) {
		websocket = new WebSocket("wss://wuyujitang.top/websocket/chat/"+userId+"/"+otherSideUserId);
	} else {
		alert('Not support websocket')
	}

	//连接发生错误的回调方法
	websocket.onerror = function() {
		alert('创建连接失败')
	};

	//连接成功建立的回调方法
	websocket.onopen = function(event) {
		//setMessageInnerHTML("open");
	}

	//接收到消息的回调方法
	websocket.onmessage = function(event) {
		console.log(event.data)
		setMessageInnerHTML(event.data);
	}

	//连接关闭的回调方法
	websocket.onclose = function() {
		//setMessageInnerHTML("close");
	}

	//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
	window.onbeforeunload = function() {
		websocket.close();
	}

	//将消息显示在网页上
	function setMessageInnerHTML(chatStr) {
		var chat = JSON.parse(chatStr)
		var util = layui.util;
		$('.main .chat_info').html($('.main .chat_info').html() + '<li class="left"><img src="' + chat.userAvatar + '" alt=""><b>' + chat.userName + '</b><i>'+util.toDateString(chat.createTime, 'MM-dd HH:mm')+'</i><div class="aaa">' + chat.msg  +'</div></li>');

		// 滚动条滚到最下面
		$('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').animate({
			scrollTop: $('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').prop('scrollHeight')
		}, 500);

	}

	//关闭连接
	function closeWebSocket() {
		websocket.close();
	}

	//发送消息
	function send(chat) {
		websocket.send(chat);
	}
	$(function () {
		//初始化聊天消息
		/*标记，第一次加载*/
		var firstLoad = true;

		//防止连续触发滚动事件
		var continuous = true;

		//加载动画
		if (total>0){
			$('.loaderbox').show()
			//页面初次加载，将最新的聊天记录插入页面
			insertMsg(dataTable.rows)
		}

		//滚动条位置设置
		$('.scrollbar-macosx').scrollTop(100)


		//滚动条到达顶部，获取历史数据
		$('.scrollbar-macosx').scroll(function () {
			var top=$(this).scrollTop()
			//排除页面初次加载
			if (!firstLoad) {
				if (pageAll>=page){
					if (top==0&&continuous){
						continuous=false;
						//console.log("触发加载")
						//加载动画
						$('.loaderbox').show()
						var url = "/system/chat/list";
						//从第二页开始加载
						var data={
							chatId:userId<otherSideUserId?userId+'-'+otherSideUserId:otherSideUserId+'-'+userId,
							pageSize: pageSize,
							pageNum: page,
							isAsc: 'desc',
							orderByColumn:'create_time',
						}
						var config = {
							url: url,
							type: "post",
							dataType: "json",
							data: data,
							beforeSend: function () {

							},
							success: function(result) {
								if (result.code===0){
									historyRecord(result.rows)
									page++;
									$('.scrollbar-macosx').scrollTop(100)
									setTimeout(function(){
										$('.loaderbox').hide()
										 continuous=true;
									}, 500);
								}else {
									$('.scrollbar-macosx').scrollTop(100)
									setTimeout(function(){
										$('.loaderbox').hide()
										 continuous=true;
									}, 500);
									layer.open({
										title: '系统提示'
										,content: '加载失败'
										,yes: function(){
											layer.closeAll();
										}
									});
								}
							}
						};
						$.ajax(config)
					}
				} else {
					$('.chat-end').show()
				}
			}
		})
		setTimeout(function(){
			$('.loaderbox').hide()
			firstLoad=false
		}, 350);

		// 发送图片
		$('.imgFileBtn').change(function(event) {


			var str = '<img src="/img/chat/theme/' + '1_bg.jpg' +'" />'

			sends_message('绿巨人', 1, str); // sends_message(昵称,头像id,聊天内容);

			// 滚动条滚到最下面
			$('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').animate({
				scrollTop: $('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').prop('scrollHeight')
			}, 500);
		});

		// 发送消息
		$('.text input').focus();
		$('#subxx').click(function(event) {
			var str = $('.text input').val(); // 获取聊天内容
			str = str.replace(/\</g,'&lt;');
			str = str.replace(/\>/g,'&gt;');
			str = str.replace(/\n/g,'<br/>');
			str = str.replace(/\[em_([0-9]*)\]/g,'<img src="/img/chat/face/$1.gif" alt="" />');
			continuous = false
			if(str!='') {

				sends_message(userName, avatar, str); // sends_message(昵称,头像id,聊天内容);


				// 滚动条滚到最下面
				$('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').animate({
					scrollTop: $('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').prop('scrollHeight')
				}, 500);

				setTimeout(function(){
					continuous=true;
				}, 500);
			}
			$('.text input').val(''); // 清空输入框
			$('.text input').focus(); // 输入框获取焦点
		});


	})

	function historyRecord(msgData) {
		var util = layui.util;
		var timeFrame = '<li class="systeminfo">\n' +
				'<span>'+util.timeAgo(msgData[0].createTime)+'</span>\n' +
				'</li>'

		$('.main .chat_info').html(timeFrame+$('.main .chat_info').html())
		for (let i = 0; i <msgData.length -1 ; i++) {
			if (msgData[i].userId==userId){
				//自己的消息
				var chat = msgData[i]
				$('.main .chat_info').html( '<li class="right"><img src="' + chat.userAvatar + '" alt=""><b>' + chat.userName + '</b><i>'+util.toDateString(chat.createTime, 'MM-dd HH:mm')+'</i><div class="aaa">' + chat.msg  +'</div></li>' +$('.main .chat_info').html() );
			}else {
				var chat = msgData[i]
				$('.main .chat_info').html('<li class="left"><img src="' + chat.userAvatar + '" alt=""><b>' + chat.userName + '</b><i>'+util.toDateString(chat.createTime, 'MM-dd HH:mm')+'</i><div class="aaa">' + chat.msg  +'</div></li>'+ $('.main .chat_info').html() );
			}
		}

	}

	/**
	 * chat 消息对象
	 * type ：right 、left
	 *
	 * */
	function insertMsg(msgData) {
		var util = layui.util;
		for (let i = msgData.length -1; i >=0 ; i--) {

			if (msgData[i].userId==userId){
				//自己的消息
				var chat = msgData[i]
				var h = new Date(chat.createTime).getHours()+8;
				var time = util.toDateString(chat.createTime, 'yyyy-MM-dd hh:mm:ss').replace('hh',h)
				$('.main .chat_info').html($('.main .chat_info').html() + '<li class="right"><img src="' + chat.userAvatar + '" alt=""><b>' + chat.userName + '</b><i>'+util.toDateString(time, 'MM-dd HH:mm')+'</i><div class="aaa">' + chat.msg  +'</div></li>');

			}else {
				var chat = msgData[i]
				var h=new Date(chat.createTime).getHours()+8;
				var time = util.toDateString(chat.createTime, 'yyyy-MM-dd hh:mm:ss').replace('hh',h)
				$('.main .chat_info').html($('.main .chat_info').html() + '<li class="left"><img src="' + chat.userAvatar + '" alt=""><b>' + chat.userName + '</b><i>'+util.toDateString(time, 'MM-dd HH:mm')+'</i><div class="aaa">' + chat.msg  +'</div></li>');
			}
		}
		var h = new Date(msgData[0].createTime).getHours()+8
		var time = util.toDateString(msgData[0].createTime, 'yyyy-MM-dd hh:mm:ss').replace('hh',h)
		var timeFrame = '<li class="systeminfo">\n' +
				'<span>'+util.timeAgo(time)+'</span>\n' +
				'</li>'
		$('.chat_info').append(timeFrame)
	}

	function sends_message (userName, userPortrait, message) {
		if(message!='') {
			var util = layui.util;
			var date = util.toDateString(new Date(), 'MM-dd HH:mm')
			$('.main .chat_info').html($('.main .chat_info').html() + '<li class="right"><img src="' + userPortrait + '" alt=""><b>' + userName + '</b><i>'+date+'</i><div class="aaa">' + message  +'</div></li>');

			var data={
				userId:userId,
				chatId:userId<otherSideUserId?userId+'-'+otherSideUserId:otherSideUserId+'-'+userId,
				userName:userName,
				userAvatar:userPortrait,
				msg:message,
				createTime:new Date(),
				msgState:'0'
			}
			send(JSON.stringify(data))
		}
	}
</script>
</html>